package com.sanqing.iframe;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.IOException;

import com.sanqing.dao.Dao;
import com.sanqing.main.*;
import com.sanqing.model.*;	 //公共类model
import com.sanqing.model.MyDocument;

public class BookLoginIFrame extends JFrame { 
    private Operator user;
    private JTextField username;
    private JPasswordField password;
    private JLabel imageLabel;  // 声明图片标签
    private ImageIcon originalIcon;  // 存储原始图片
    private static Operator user1;
    
    //构造方法
    public BookLoginIFrame(){ 
        super(); 
        final BorderLayout borderLayout = new BorderLayout();//创建布局管理器
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭按钮处理事件
        borderLayout.setVgap(10); //设置组件之间垂直距离;
        getContentPane().setLayout(borderLayout); //使用布局管理器
        setTitle("图书馆管理系统登录"); //设置窗体标题
        
        // 设置窗口位置和大小
        Toolkit tool = Toolkit.getDefaultToolkit(); 
        Dimension screenSize = tool.getScreenSize();
        setSize(400, 200);
        setLocation((screenSize.width - getWidth())/2, (screenSize.height - getHeight())/2);
        
        // 创建主面板
        final JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setBorder(new EmptyBorder(0, 0, 0, 0));
        getContentPane().add(mainPanel);
        
        // 创建并添加图片标签
        imageLabel = new JLabel();
        loadAndDisplayImage();  // 加载并显示图片
        
        // 添加组件监听器，监听窗口大小变化
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                resizeImage();  // 窗口大小改变时调整图片大小
            }
        });
        
        mainPanel.add(imageLabel, BorderLayout.NORTH);
        
        // 创建中心面板
        final JPanel centerPanel = new JPanel();
        final GridLayout gridLayout = new GridLayout(2, 2);
        gridLayout.setHgap(5);
        gridLayout.setVgap(20);
        
        centerPanel.setLayout(gridLayout);
        mainPanel.add(centerPanel);
        
        // 添加用户名和密码输入组件
        final JLabel userNameLabel = new JLabel();
        userNameLabel.setHorizontalAlignment(SwingConstants.CENTER);
        centerPanel.add(userNameLabel);
        userNameLabel.setText("用 户 名：");
        
        username = new JTextField(20);
        centerPanel.add(username);
        
        final JLabel passwordLabel = new JLabel();
        passwordLabel.setHorizontalAlignment(SwingConstants.CENTER);
        centerPanel.add(passwordLabel);
        passwordLabel.setText("密 码：");
        
        password = new JPasswordField(20);
        password.setDocument(new MyDocument(6));
        password.setEchoChar('*');
        centerPanel.add(password);
        
        // 创建底部面板
        final JPanel southPanel = new JPanel();
        mainPanel.add(southPanel, BorderLayout.SOUTH);
        
        // 添加登录按钮
        JButton login = new JButton();
        login.addActionListener(new BookLoginAction());
        login.setText("登录");
        southPanel.add(login);
        
        // 设置密码框回车事件
        password.addKeyListener(new KeyAdapter() {
            public void keyPressed(final KeyEvent e) {
                if (e.getKeyCode() == 10)
                    login.doClick();
            }
        });
        
        // 添加重置按钮
        JButton reset = new JButton();
        reset.addActionListener(new BookResetAction());
        reset.setText("重置");
        southPanel.add(reset);
        
        setVisible(true);
        setResizable(true);
    }
    
    // 加载并显示图片
    private void loadAndDisplayImage() {
        try {
            // 尝试从类路径加载图片
            java.net.URL imgUrl = getClass().getResource("/res/login.jpg");
            if (imgUrl != null) {
                originalIcon = new ImageIcon(imgUrl);
            } else {
                // 如果从类路径加载失败，尝试从文件系统加载
                originalIcon = new ImageIcon("res/login.jpg");
            }
            
            // 初始显示图片
            resizeImage();
            
        } catch (Exception e) {
            // 图片加载失败，显示错误信息
            imageLabel.setText("图片加载失败");
            imageLabel.setHorizontalAlignment(JLabel.CENTER);
            imageLabel.setOpaque(true);
            imageLabel.setBackground(Color.RED);
            e.printStackTrace();
        }
    }
    
    // 调整图片大小以适应标签
    private void resizeImage() {
        if (originalIcon == null || originalIcon.getImage() == null) {
            return;
        }
        
        // 获取标签的当前大小
        int labelWidth = imageLabel.getWidth();
        int labelHeight = imageLabel.getHeight();
        
        // 如果标签大小为0，使用窗口初始大小
        if (labelWidth <= 0 || labelHeight <= 0) {
            labelWidth = 400;  // 默认宽度
            labelHeight = 60;   // 默认高度
        }
        
        // 调整图片大小
        Image resizedImage = originalIcon.getImage().getScaledInstance(
            labelWidth, 
            labelHeight, 
            Image.SCALE_SMOOTH
        );
        
        // 更新标签显示的图片
        imageLabel.setIcon(new ImageIcon(resizedImage));
        imageLabel.setPreferredSize(new Dimension(labelWidth, labelHeight));
    }
	public class BookLoginAction implements ActionListener{

		public void actionPerformed(final ActionEvent e) {
			Operator user = Dao.check(username.getText(),new String(password.getPassword()));//调用DAO方法
			if(user.getISBN()!=null)
			{
				common.UserName=username.getText();
				user1=user;
				try {
					if(user.getGrade()==1)
					{
						Library frame=new Library();//创建一个主窗体
						frame.setVisible(true);//设置其可见
						BookLoginIFrame.this.setVisible(false);//设置登录窗体为不显示
					}
					else
					{
						ReaderFrame frame=new ReaderFrame();//创建一个主窗体
						frame.setVisible(true);//设置其可见
						BookLoginIFrame.this.setVisible(false);//设置登录窗体为不显示
					}
					
					
				}catch(Exception ex) {
					ex.printStackTrace();
				}
				}else {
					JOptionPane.showMessageDialog(null,"请输入正确的用户名和密码！");//弹出提示框
					username.setText("");//设置用户名输框为空
					password.setText("");//设置密码输入框为空
				}
		  }	
	}
	public class BookResetAction implements ActionListener{
		public void actionPerformed(final ActionEvent e){
			username.setText("");//设置用户名输入框为空
			password.setText("");//设置密码输入框为空
		}
	}
	public static Operator getOperator()
	{
		return user1;
	}

}
